using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MvcDemo09.Db;
using MvcDemo09.Models;
using MvcDemo09.Repository;
using MvcDemo09.ResultModel;

namespace MvcDemo09.Controllers
{
    public class StudentController : Controller
    {
        private readonly MvcDb _db;
        private readonly EfRepository<Student> Restu;
        public StudentController()
        {
            _db = new MvcDb();
            Restu = new EfRepository<Student>();
            var ReSchool = new EfRepository<School>();
            var school = ReSchool.Table.Where(x => x.IsDel == false).FirstOrDefault();
            if (school == null)
            {
                var schools = new School
                {
                    Name = "1中"
                };

                ReSchool.Insert(schools);
            }
        }
        public IActionResult Index()
        {
            var Student = _db.Student.Where(x => x.IsDel == false).ToArray();
            return View(Student);
        }
        public IActionResult CreateOrEdit(int id)
        {
            var student = Restu.GetById(id);
            return View(student);
        }
        public IActionResult Save(Student student)
        {
            if (student == null || student.Id <= 0)
            {
                Restu.Insert(student);
            }
            else
            {
                Restu.Update(student);
            }
            return Ok();
        }
        public IActionResult Delete(int id)
        {
            Restu.Delete(id);
            return RedirectToAction("Index");
        }
        public IActionResult Query(Keyword keyword)
        {
            var db = new MvcDb();

            List<Student> students;
            if (keyword.word == null || keyword.word.Length <= 0)
            {
               students= db.Student.Where(x => x.IsDel == false).ToList();
            }
            else
            {
                students = db.Student.Where(x => x.IsDel == false && x.Name.Contains(keyword.word)).ToList();
            }
            return Json(students);
        }
    }
}